package com.zboin.framework.aspect;

import com.alibaba.fastjson2.JSON;
import com.zboin.common.domain.LoginBody;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;

/**
 * @author zhboom
 * @date 2025/6/1 22:22
 */
@Slf4j
@Aspect
@Component
public class WebLogAspect {

    @Pointcut("execution(public * com.zboin.controller.*Controller.*(..))")
    public void wegLog() { }

    @Around("wegLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();

        Object proceed = joinPoint.proceed();

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        StringBuffer requestUrl = request.getRequestURL();
        String methodName = joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        if (requestUrl.indexOf("/login") >= 0) {
            // password clear
            ((LoginBody) args[0]).setPassword("");
        }
        log.info("""
                Request Url: {}
                Method : {}
                Params : {}
                Request cost time : {}
                Request result : {}
                """,
                requestUrl, methodName, Arrays.toString(args),
                (System.currentTimeMillis() - start),
                JSON.toJSONString(proceed));

        return proceed;
    }
}
